package com.cdshangpai.utils.offlinecache;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.cdshangpai.utils.api.Api;
import com.cdshangpai.utils.db.FormDb;
import com.cdshangpai.utils.db.beans.Form;

import java.util.ArrayList;

//离线表单提交
public class FormSubmit {
    //是否处于提交状态
    private static boolean busy=false;
    private static int askCount=0;
    private static NetworkState networkState=new NetworkState();
    private Api api=new Api();

    //开始提交,页面提交按钮点击和网络由关闭切换到打开状态，通知一次执行
    public synchronized void notifySubmit()
    {
        askCount++;
        if(busy||!networkState.isOnline())
        {
            return;
        }
        busy=true;
        boolean submitOk=doSubmit();
        if(submitOk)
        {
            askCount--;
        }
        busy=false;
    }

    //执行提交逻辑处理
    public boolean doSubmit()
    {
        ArrayList<Form> forms=pickDbForm();
        if(forms.size()==0)
        {
            //没有数据
            return true;
        }
        boolean submitOk=submitToServer(forms);
        if(submitOk)
        {
            //成功提交服务器
            ArrayList<Integer> ids=new ArrayList<>();
            for(Form item:forms){
                ids.add(item.id);
            };
            deletSuccessSubmitForm(ids);
            return true;
        }else
        {
            //提交服务器失败
            return false;
        }
    }

    public boolean submitToServer(ArrayList<Form> forms){
        return api.submitForm(forms);
    }

    private JSONArray string2JsonArray(String sou)
    {
        if(TextUtils.isEmpty(sou))
        {
            return new JSONArray();
        }
        return JSONArray.parseArray("["+sou+"]");
    }


    //查询本地缓存需要提交的表单
    public ArrayList<Form> pickDbForm()
    {
        FormDb formDb=new FormDb();
        return formDb.query();
    }

    //成功提交后，删除成功提交的数据
    public void deletSuccessSubmitForm(ArrayList<Integer> ids)
    {
        FormDb formDb=new FormDb();
        formDb.deleteByIds(ids.toArray(new Integer[ids.size()]));
    }
}
